package org.zjvis.datascience.common.graph.model;

import lombok.Data;
import org.zjvis.datascience.common.vo.graph.LinkVO;
import org.zjvis.datascience.common.vo.graph.NodeVO;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @description Graph
 * @date 2021-12-29
 */
@Data
public class Graph {
    private Map<String, Node> nodeMap;
    private Map<String, Link> linkMap;


    public Graph(List<NodeVO> nodes, List<LinkVO> links) {
        nodeMap = new ConcurrentHashMap<>();
        linkMap = new ConcurrentHashMap<>();
        nodeMap = nodes.parallelStream()
                .map(vo->new Node(vo.getId(), vo.getCategoryId()))
                .collect(Collectors.toMap(Node::getId, n->n));
        links.parallelStream().forEach(vo->{
            Node src = nodeMap.get(vo.getSource());
            Node tar = nodeMap.get(vo.getTarget());
            Link link = new Link(vo.getId(), src, tar, vo.getEdgeId());
            linkMap.put(vo.getId(), link);
            nodeMap.get(vo.getSource()).getHeadOut().add(link);
            nodeMap.get(vo.getTarget()).getHeadIn().add(link);
        });
    }

    public List<Link> getOutLinks(String nodeId) {
        return nodeMap.get(nodeId).getHeadOut();
    }

    public List<Link> getInLinks(String nodeId) {
        return nodeMap.get(nodeId).getHeadIn();
    }

}
